/** @jsxImportSource @emotion/react */
//import { jsx, Global } from "@emotion/react";
import * as React from "react";
//import Editor, { tryValue } from "./Editor";
//import { ImageUpload } from "./ImageUpload";
//import { Image } from "./Image";
//import { Value } from "slate";
//import debug from "debug";
//import initialValue from "./value.json";
//import { Ingredient } from "./RecipeList";
import {
  Input,
  Text,
  Button,
  useTheme,
  InputBaseProps,
  useToast,
  LayerLoading,
  Container,
  Select,
  ListItem,
  Avatar,
  MenuList,
  MenuItem,
  IconPackage,
  IconButton,
  IconMoreVertical,
  List, InputLine, SuffixInput, ButtonRefComp
} from "customize-easy-ui-component";
//import { useCreateDevice, useUpdateDevice } from "./db";

//import { Link as RouterLink, useLocation } from "wouter";
import { css } from "@emotion/react";
//import { Link as RouterLink } from "wouter";
import {设备种类,设备类别,设备品种} from "./../dict/eqpComm"
//import { InspectRecordLayout, SelectHookfork } from "../report/comp/base";
import { 管道单元 as PipingUnitComp } from "./edit/管道单元";
import { useThrottle } from "../hooks/useHelpers";
import useRegisterMutation from "../common/useRegisterMutation";
//import useCreateDeviceMutation from "./useCreateDeviceMutation";
import { Link as RouterLink } from "../routing/Link";
import {useContext} from "react";
import RoutingContext from "../routing/RoutingContext";
import useRemovePipingUnitMutation from "./useRemovePipingUnitMutation";
import {ContainLine, TransparentInput} from "../comp/base";
import useUpdateDeviceMutation from "./useUpdatePipingUnitMutation";
import NewPipingUnit from "./NewPipingUnit";
import {PressureLayout} from "../report/common/pressure";
//const log = debug("app:Compose");



interface ComposePipingUnitProps {
  id?: string;
  readOnly?: boolean;
  dt?:any;
}

export const ComposePipingUnit: React.FunctionComponent<ComposePipingUnitProps> = ({
  readOnly,
  id,
  dt :eqp =null,
}) => {
  const theme = useTheme();
  const toast = useToast();
 // const {user,} = useSession();
  //const [loading, setLoading] = React.useState(false);
  const [editing, ] = React.useState(!readOnly|| true);
  /* const [content, ] = React.useState(() => {
        return defaultDescription
          ? ''
          : null;
      });　 */

  //这里ingredients挂载初始化后只能setIngredients改了，useState()后面参数变动就不再起作用了。
  //const [ingredients, setIngredients] = React.useState<any>( dt||{} );

  //const [, setLocation] = useLocation();
 // const [eqpType, setEqpType] = React.useState(undefined);
  //可编辑的设备数据表 要创建新设备=null,首先生成ID,随后刷新路由再进来 eqp有基本数据了。
  //const [eqp, setEqp] = React.useState(dt);    //为了更改数据用的。
  const {history } = useContext(RoutingContext);

  const {call:removeEqpfunc,doing, result:isok}= useRemovePipingUnitMutation();
  const {call:updateEqpfunc,isInFlight:saving }= useUpdateDeviceMutation();


  async function updateDevice( eqp :any
  ) {
    //查询输出eqp已经带入 rno 字段； 但是输入inp模型定义中不存在 rno ；必须屏蔽掉，否则是非法请求！
    //特殊情况！输出的不能直接绕回给输入字段。输出Unit对象,输入确只要UnitID的; 发送时关联对象映射: desu=>desu.id;
    const sendInp={ ...eqp, rno:undefined, __typename:undefined, pipe:undefined, id:undefined,
          desu: eqp.desu?.id, insu: eqp.insu?.id, ad: eqp.ad?.id,
          isp2:undefined,isp1:undefined,ispsv:undefined, ninsp:undefined,reg:undefined,
          dets:undefined, crDate:undefined,
          svp: JSON.stringify(eqp.svp),  pa: JSON.stringify(eqp.pa),
        };
    try {
      console.log("保存updateDevice之前 eqp=",eqp,"sendInp=",sendInp);
      updateEqpfunc( id!, sendInp);
    } catch (err: any) {
      //setLoading(false);
      toast({
        title: "捕获errcc错",
        subtitle: err.message,
        intent: "error"
      });
      console.log("捕获err打了吗", err);
    }
  }

  //点击前触发子孙组件的各个输入框onBlur()都触发干净了。
  const commitBlurRef =React.useRef<HTMLDivElement | null>(null);

  // const paramsNode =React.useMemo(() => {
  //   return  <PipingUnitComp  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>;
  // }, [eqp,id,updateDevice]);

  return (
    <div
      css={{
        [theme.mediaQueries.md]: {
          height: "auto",
          display: "block"
        }
      }}
    >
      <div
        css={{  //控制小屏时的导航条底下的整个页面滚动。
          flex: 1,
          [theme.mediaQueries.md]: {
            flex: "none"
          }
        }}
      >
        <div>
          <Container>
            <div
              css={{
                paddingTop: theme.spaces.lg,
                paddingBottom: theme.spaces.lg
              }}
            >
              <div>
                <Text variant="h5">该条管道单元的明细</Text>

                    <div key={1}>
                      {editing ? (
                      <div>
                        <ContainLine display={'管道编号'}>
                            <TransparentInput readOnly value={eqp?.code || ''} />
                        </ContainLine>
                        <ContainLine display={'使用单位'}>
                          <TransparentInput readOnly value={eqp?.pipe.useu?.company.name || ''} />
                        </ContainLine>
                        <ContainLine display={'装置名称'}>
                          <TransparentInput readOnly value={eqp?.pipe.titl || ''} />
                        </ContainLine>
                        <ContainLine display={'管道单元登记编号'}>
                          <TransparentInput readOnly value={eqp?.rno || ''} />
                        </ContainLine>
                      </div>
                      ) : (
                        <div
                          css={{
                            backgroundColor: false
                              ? theme.colors.palette.blue.lightest
                              : "transparent",
                            display: "flex",
                            marginLeft: "-0.25rem",
                            paddingLeft: "0.25rem",
                            marginRight: "-0.25rem",
                            paddingRight: "0.25rem",
                            // borderRadius: "0.25rem",
                            marginBottom: theme.spaces.xs,
                            justifyContent: "space-between",
                            [theme.mediaQueries.md]: {
                              width: "500px"
                            }
                          }}
                        >
                          <Text
                            css={{
                              paddingRight: theme.spaces.xs,
                              backgroundColor: false
                                ? theme.colors.palette.blue.lightest
                                : "white"
                            }}
                          >
                            设备号：{eqp.cod}
                          </Text>
                          <div
                            css={{
                              flex: 1,
                              borderBottom: `1px dashed ${
                                theme.colors.border.muted
                              }`,
                              marginBottom: "6px"
                            }}
                          />
                          <Text
                            css={{
                              paddingLeft: theme.spaces.xs,
                              backgroundColor: false
                                ? theme.colors.palette.blue.lightest
                                : "white"
                            }}
                          >
                            监察识别码：{eqp.oid}
                          </Text>
                        </div>
                      )}
                      <br/>
                      <Text>暂时无独立管道单元库，目前设备是导入一个就积累一个的设备列表，待完善</Text>
                      {/* 【严重毛病】必须加key={id} 否则可能底下的组件根本不会重新 remount导致内部状态变量不会跟着eqp数据而更新 */}
                      <PipingUnitComp key={id} id={id} readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                    </div>

              </div>
              <Button
                  intent="primary"
                  css={{ marginLeft: theme.spaces.sm }}
                  onPress={() => {  //按钮里面看不到最新的input取值的。
                    //TODO: 查询设备null，必须删除掉设备； 暂时固定ID
                    removeEqpfunc(eqp.id, eqp?.pipe.id);
                  }}
              >
                淘汰这个管道单元
              </Button>
{/*              {editing && <ButtonRefComp
                intent="primary"
                disabled ={false}
                ref={commitBlurRef}
                css={{ marginLeft: theme.spaces.sm }}
                onPointerOver={(e :any) => {
                  //似乎没有效果啊，多套了一层
                  commitBlurRef!.current!.focus();
                }}
                onPress={ async () => {
                  await updateDevice({ ...eqp }  );
                } }
              >
                更新@Deprecated设备信息到后端服务器
              </ButtonRefComp>
              }*/}
            </div>
          </Container>
        </div>
      </div>

    </div>
  );
};

